package cn.com.jit;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.*;
import java.io.File;
import java.io.IOException;

public class SqlExtractorFromMybatisXml {

    private static final String FILE_PATH = "D:\\JIT_workspaces\\workspace\\FCMS_3.2\\platform-fcms-provide\\modules\\fcms-business\\src\\main\\resources\\mapper\\account\\AccountMapper.xml";

    public static void main(String[] args) {
        extractSqlStatements(FILE_PATH);
    }

    public static void extractSqlStatements(String filePath) {
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser saxParser = factory.newSAXParser();
            MySaxHandler handler = new MySaxHandler();
            saxParser.parse(new File(filePath), handler);
        } catch (Exception e) {
            System.err.println("Error parsing the XML file: " + e.getMessage());
        }
    }

    static class MySaxHandler extends DefaultHandler {
        private StringBuilder currentText = new StringBuilder();
        private boolean inSelect = false;
        private boolean inUpdate = false;
        private int lineNumber = -1;

        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            lineNumber++;
            if (qName.equalsIgnoreCase("select")) {
                inSelect = true;
            } else if (qName.equalsIgnoreCase("update")) {
                inUpdate = true;
            }
        }

        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {
            if (inSelect || inUpdate) {
                String text = currentText.toString().trim();
                if (!text.isEmpty()) {
                    if (inSelect) {
                        System.out.println("SQL (" + lineNumber + "): " + text);
                    } else if (inUpdate) {
                        System.out.println("SQL (" + lineNumber + "): " + text);
                    }
                }
                currentText = new StringBuilder();
                inSelect = false;
                inUpdate = false;
            }
        }

        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            currentText.append(ch, start, length);
        }
    }
}

